package com.common.weapp.service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.stereotype.Service;

@Service
public class WeTokenService {
	
	@Autowired
	private OAuth2ClientProperties oAuth2ClientProperties;
	
	@Autowired
	private AuthorizationServerTokenServices tokenServices;
	
	@Autowired
	private ClientDetailsService clientDetailsService;

	public OAuth2AccessToken createAccessToken(Authentication authentication, Map<String, String> params){
		
		String clientId = oAuth2ClientProperties.getClientId();
	    Set<String> scopes = new HashSet<>();
	    scopes.add("all");
		    
	    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
	    
		TokenRequest tokenRequest = new TokenRequest(params, clientId, scopes, "password");
		OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
		
		OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
			
		OAuth2AccessToken token = tokenServices.createAccessToken(oAuth2Authentication);
		
		return token;
	}
}
